/*
 * Copyright (C) 2005 Johan Maasing johan at zoom.nu Licensed under the Apache
 * License, Version 2.0 (the "License"); you may not use this file except in
 * compliance with the License. You may obtain a copy of the License at
 * http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law
 * or agreed to in writing, software distributed under the License is
 * distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
 * KIND, either express or implied. See the License for the specific language
 * governing permissions and limitations under the License.
 */
package nu.zoom.swing.desktop.plugin.portunis.impl;

import java.awt.event.ActionEvent;
import java.awt.event.KeyEvent;
import java.io.File;
import java.io.IOException;
import java.security.KeyStoreException;
import java.security.NoSuchAlgorithmException;
import java.security.cert.CertificateException;

import javax.swing.JFileChooser;
import javax.swing.JOptionPane;

import nu.zoom.swing.desktop.Workbench;
import nu.zoom.swing.desktop.common.BackendException;
import nu.zoom.swing.desktop.common.action.WorkbenchMessageAction;
import nu.zoom.swing.desktop.plugin.portunis.ApplicationPreferences;
import nu.zoom.swing.desktop.plugin.portunis.KeyStoreHandler;
import nu.zoom.swing.desktop.plugin.portunis.KeyStoreWrapper;

import org.ops4j.gaderian.Messages;

/**
 * An action to save (save as) a keystore to disk.
 * 
 * @version $Revision: 1.1 $
 * @author $Author: johan $
 */
public class SaveKeyStoreAction extends WorkbenchMessageAction
{

	private ApplicationPreferences prefs;
	private boolean saveAs;
	private KeyStoreWrapper wrapper;
	private Workbench workbench;
	private KeyStoreHandler keyStoreHandler;
	private KeyStorePlugIn plugin;

	public SaveKeyStoreAction(KeyStorePlugIn plugin,
			KeyStoreHandler keyStoreHandler, Workbench workbench,
			ApplicationPreferences prefs, Messages messages,
			KeyStoreWrapper wrapper, boolean saveAs) {
		super(messages);
		if (wrapper == null) {
			throw new IllegalArgumentException("wrapper can not be null");
		}
		this.wrapper = wrapper;
		this.saveAs = saveAs;
		this.workbench = workbench;
		this.keyStoreHandler = keyStoreHandler;
		this.prefs = prefs;
		this.plugin = plugin;
		if (saveAs) {
			setNameFromMessages("keystore.menu.saveAs");
			setIconFromMessages("keystore.menu.saveAs.icon");
			setToolTipFromMessages("keystore.menu.saveAs.tooltip");
			setMnemonicKey(KeyEvent.VK_A);
			setAcceleratorKey(KeyEvent.VK_A, KeyEvent.CTRL_DOWN_MASK);
		} else {
			setNameFromMessages("keystore.menu.save");
			setIconFromMessages("keystore.menu.save.icon");
			setToolTipFromMessages("keystore.menu.save.tooltip");
			setMnemonicKey(KeyEvent.VK_S);
			setAcceleratorKey(KeyEvent.VK_S, KeyEvent.CTRL_DOWN_MASK);
		}
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see java.awt.event.ActionListener#actionPerformed(java.awt.event.ActionEvent)
	 */
	public void actionPerformed(ActionEvent e)
	{
		try {
			if (!saveAs && (wrapper.getFile() != null)) {
				save();
			} else {
				saveAs();
			}
		} catch (Exception exc) {
			workbench.getErrorReporter().reportError(
					messages.getMessage("keystore.menu.save.error"), exc);
		}
	}

	private void save() throws KeyStoreException, NoSuchAlgorithmException,
			CertificateException, IOException
	{
		CreatePasswordDialog passwordDlg = new CreatePasswordDialog(workbench,
				messages, "keystore.save.password.title",
				"keystore.save.password");
		passwordDlg.pack();
		passwordDlg.setVisible(true);
		if (passwordDlg.isCloseOK()) {
			keyStoreHandler.saveKeyStore(wrapper, passwordDlg.getPassword());
		}
	}

	private void saveAs() throws KeyStoreException, NoSuchAlgorithmException,
			CertificateException, IOException
	{
		JFileChooser chooser = new JFileChooser();
		try {
			String startdirectory = prefs.getFileChooserStartDirectory();
			if (startdirectory != null) {
				chooser.setCurrentDirectory(new File(startdirectory));
			}
		} catch (BackendException e) {
		}
		chooser.setFileSelectionMode(JFileChooser.FILES_ONLY);
		chooser.setMultiSelectionEnabled(false);
		int chooserAction = chooser.showSaveDialog(workbench.getDialogOwner());
		if (chooserAction == JFileChooser.APPROVE_OPTION) {
			File keystoreFile = chooser.getSelectedFile();
			if (keystoreFile != null) {
				if (keystoreFile.exists()) {
					int option = JOptionPane
							.showConfirmDialog(
									workbench.getDialogOwner(),
									messages
											.getMessage("keystore.menu.save.overwrite"),
									messages
											.getMessage("keystore.menu.save.overwrite.title"),
									JOptionPane.YES_NO_OPTION);
					if (option == JOptionPane.NO_OPTION) {
						return;
					}
				}
				CreatePasswordDialog passwordDlg = new CreatePasswordDialog(
						workbench, messages, "keystore.save.password.title",
						"keystore.save.password");
				passwordDlg.pack();
				passwordDlg.setVisible(true);
				if (passwordDlg.isCloseOK()) {
					keyStoreHandler.saveKeyStoreAs(wrapper, keystoreFile,
							passwordDlg.getPassword());
					plugin.loadKeystore(keystoreFile, wrapper.getType(),
							passwordDlg.getPassword());
					try {
						prefs.setFileChooserStartDirectory(keystoreFile
								.getParentFile().getAbsolutePath());
					} catch (BackendException e1) {
					}
				}
			}
		}
	}
}
